<template>
	<view class="order-list">
		<!-- 导航栏 -->
		<view class="navbar">
			<view class="navbar-left" @click="goBack">
				<text class="back-icon">‹</text>
			</view>
			<view class="navbar-title">我的订单</view>
			<view class="navbar-right"></view>
		</view>
		
		<!-- 订单状态筛选 -->
		<view class="status-tabs">
			<view 
				v-for="(tab, index) in statusTabs" 
				:key="index"
				:class="['tab-item', { active: currentTab === index }]"
				@click="switchTab(index)"
			>
				{{ tab.name }}
			</view>
		</view>
		
		<!-- 订单列表 -->
		<scroll-view 
			scroll-y="true" 
			class="order-scroll"
			@scrolltolower="loadMore"
			refresher-enabled="true"
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view v-if="orderList.length > 0">
				<view 
					v-for="order in orderList" 
					:key="order.id"
					class="order-item"
					@click="goToDetail(order.id)"
				>
					<!-- 订单头部 -->
					<view class="order-header">
						<view class="order-number">订单号：{{ order.orderNumber }}</view>
						<view :class="['order-status', getStatusClass(order.status)]">{{ getStatusText(order.status) }}</view>
					</view>
					
					<!-- 商品信息 -->
					<view class="product-info">
						<image 
						:src="getFirstImage(order.productImage) || '/static/default-product.png'" 
						class="product-image"
						mode="aspectFill"
						@error="handleImageError"
					></image>
						<view class="product-details">
							<view class="product-title">{{ order.productTitle }}</view>
							<view class="product-price">¥{{ order.finalPrice }}</view>
							<view class="order-time">{{ formatTime(order.createdAt) }}</view>
						</view>
					</view>
					
					<!-- 订单操作 -->
					<view class="order-actions">
						<button 
							v-if="canCancel(order.status)"
							class="action-btn cancel-btn"
							@click.stop="cancelOrder(order.id)"
						>
							取消订单
						</button>
						<button 
						v-if="canConfirm(order.status)"
						class="action-btn confirm-btn"
						@click.stop="handleConfirm(order)"
					>
						{{ getConfirmButtonText(order.status) }}
					</button>
						<button 
							class="action-btn detail-btn"
							@click.stop="goToDetail(order.id)"
						>
							查看详情
						</button>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-else-if="!loading" class="empty-state">
				<image src="/static/empty-order.png" class="empty-image"></image>
				<text class="empty-text">暂无订单</text>
			</view>
			
			<!-- 加载更多 -->
			<view v-if="hasMore && orderList.length > 0" class="load-more">
				<view class="load-more-wrapper">
				<view v-if="loadMoreStatus === 'loading'" class="loading">
					<text class="loading-text">加载中...</text>
				</view>
				<view v-else-if="loadMoreStatus === 'noMore'" class="no-more">
					<text class="no-more-text">没有更多了</text>
				</view>
				<view v-else class="load-more">
					<text class="load-more-text">上拉加载更多</text>
				</view>
			</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { getBuyerOrders, getSellerOrders, cancelOrder as cancelOrderApi, confirmReceipt as confirmReceiptApi, sellerConfirmOrder as sellerConfirmOrderApi } from '@/api/order.js'
import { ORDER_STATUS, ORDER_STATUS_TEXT } from '@/api/order.js'
import { API_BASE_URL } from '@/utils/config.js'

export default {
	data() {
		return {
			currentTab: 0,
			statusTabs: [
				{ name: '全部', status: null },
				{ name: '待确认', status: ORDER_STATUS.PENDING_SELLER_CONFIRM },
				{ name: '待收货', status: ORDER_STATUS.PENDING_DELIVERY },
				{ name: '已完成', status: ORDER_STATUS.COMPLETED },
				{ name: '已取消', status: ORDER_STATUS.CANCELLED }
			],
			orderList: [],
			loading: false,
			refreshing: false,
			hasMore: true,
			loadMoreStatus: 'more',
			page: 1,
			pageSize: 10,
			userType: 'buyer' // buyer: 买家, seller: 卖家
		}
	},
	onLoad(options) {
		// 从参数获取用户类型
		if (options.type) {
			this.userType = options.type
		}
		
		// 设置导航栏标题
		uni.setNavigationBarTitle({
			title: this.userType === 'seller' ? '我的销售' : '我的订单'
		})
		
		this.loadOrderList()
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 切换标签
		switchTab(index) {
			this.currentTab = index
			this.page = 1
			this.hasMore = true
			this.orderList = []
			this.loadOrderList()
		},
		
		// 加载订单列表
		async loadOrderList() {
			if (this.loading) return
			
			this.loading = true
			this.loadMoreStatus = 'loading'
			
			try {
				const currentStatus = this.statusTabs[this.currentTab].status
				let response
				
				if (this.userType === 'seller') {
					response = await getSellerOrders(currentStatus)
				} else {
					response = await getBuyerOrders(currentStatus)
				}
				
				// 适配实际的API响应格式 {code: 200, message: "操作成功", data: Array}
			if (response && response.code === 200) {
				const newOrders = response.data || []
				
				if (this.page === 1) {
					this.orderList = newOrders
				} else {
					// 过滤重复的订单，避免key重复
					const existingIds = new Set(this.orderList.map(order => order.id))
					const uniqueNewOrders = newOrders.filter(order => !existingIds.has(order.id))
					this.orderList.push(...uniqueNewOrders)
				}
				
				// 判断是否还有更多数据
				this.hasMore = newOrders.length >= this.pageSize
				this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
			} else {
					uni.showToast({
						title: response.message || '加载失败',
						icon: 'none'
					})
					this.loadMoreStatus = 'more'
				}
			} catch (error) {
				console.error('加载订单列表失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
				this.loadMoreStatus = 'more'
			} finally {
				this.loading = false
				this.refreshing = false
			}
		},
		
		// 下拉刷新
		onRefresh() {
			this.refreshing = true
			this.page = 1
			this.hasMore = true
			this.orderList = []
			this.loadOrderList()
		},
		
		// 加载更多
		loadMore() {
			if (this.hasMore && !this.loading) {
				this.page++
				this.loadOrderList()
			}
		},
		
		// 获取状态文本
		getStatusText(status) {
			// 对于待卖家确认状态，根据用户角色显示不同文本
			if (status === ORDER_STATUS.PENDING_SELLER_CONFIRM) {
				return this.userType === 'seller' ? '待确认' : '待卖家确认'
			}
			return ORDER_STATUS_TEXT[status] || '未知状态'
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			switch (status) {
				case ORDER_STATUS.PENDING_SELLER_CONFIRM:
					return 'status-pending'
				case ORDER_STATUS.PENDING_DELIVERY:
					return 'status-shipping'
				case ORDER_STATUS.COMPLETED:
					return 'status-completed'
				case ORDER_STATUS.CANCELLED:
					return 'status-cancelled'
				default:
					return 'status-default'
			}
		},
		
		// 是否可以取消订单
		canCancel(status) {
			return status === ORDER_STATUS.PENDING_SELLER_CONFIRM
		},
		
		// 是否可以确认
		canConfirm(status) {
			// 卖家在待确认状态下可以确认订单
			if (this.userType === 'seller' && status === ORDER_STATUS.PENDING_SELLER_CONFIRM) {
				return true
			}
			// 买家在待收货状态下可以确认收货
			if (this.userType === 'buyer' && status === ORDER_STATUS.PENDING_DELIVERY) {
				return true
			}
			return false
		},
		
		// 获取确认按钮文本
		getConfirmButtonText(status) {
			if (this.userType === 'seller' && status === ORDER_STATUS.PENDING_SELLER_CONFIRM) {
				return '确认订单'
			}
			if (this.userType === 'buyer' && status === ORDER_STATUS.PENDING_DELIVERY) {
				return '确认收货'
			}
			return '确认'
		},
		
		// 处理确认操作
		async handleConfirm(order) {
			if (this.userType === 'seller' && order.status === ORDER_STATUS.PENDING_SELLER_CONFIRM) {
				// 卖家确认订单
				await this.sellerConfirmOrder(order.id)
			} else if (this.userType === 'buyer' && order.status === ORDER_STATUS.PENDING_DELIVERY) {
				// 买家确认收货
				await this.confirmReceipt(order.id)
			}
		},
		
		// 卖家确认订单
		async sellerConfirmOrder(orderId) {
			uni.showModal({
				title: '确认订单',
				content: '确定要确认这个订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await sellerConfirmOrderApi(orderId, {
								sellerMessage: '订单已确认'
							})
							
							if (response && response.code === 200) {
								uni.showToast({
									title: '确认成功',
									icon: 'success'
								})
								// 刷新订单列表
								this.loadOrders()
							} else {
								uni.showToast({
									title: response.message || '确认失败',
									icon: 'none'
								})
							}
						} catch (error) {
							console.error('确认订单失败:', error)
							uni.showToast({
								title: '网络错误',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 取消订单
		async cancelOrder(orderId) {
			uni.showModal({
				title: '确认取消',
				content: '确定要取消这个订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await cancelOrderApi(orderId, {
								reason: '用户主动取消'
							})
							
							if (response.success) {
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								})
								this.onRefresh()
							} else {
								uni.showToast({
									title: response.message || '取消失败',
									icon: 'none'
								})
							}
						} catch (error) {
							console.error('取消订单失败:', error)
							uni.showToast({
								title: '网络错误',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 确认收货
		async confirmReceipt(orderId) {
			uni.showModal({
				title: '确认收货',
				content: '确定已收到商品吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await confirmReceiptApi(orderId)
							
							if (response.success) {
								uni.showToast({
									title: '确认成功',
									icon: 'success'
								})
								this.onRefresh()
							} else {
								uni.showToast({
									title: response.message || '确认失败',
									icon: 'none'
								})
							}
						} catch (error) {
							console.error('确认收货失败:', error)
							uni.showToast({
								title: '网络错误',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 跳转到订单详情
		goToDetail(orderId) {
			uni.navigateTo({
				url: `/pages/order/detail?id=${orderId}`
			})
		},
		
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return ''
			
			const date = new Date(timeStr)
			const now = new Date()
			const diff = now - date
			
			// 小于1分钟
			if (diff < 60000) {
				return '刚刚'
			}
			
			// 小于1小时
			if (diff < 3600000) {
				return Math.floor(diff / 60000) + '分钟前'
			}
			
			// 小于1天
			if (diff < 86400000) {
				return Math.floor(diff / 3600000) + '小时前'
			}
			
			// 大于1天，显示具体日期
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			return `${month}-${day}`
		},
		
		// 获取第一张图片
		getFirstImage(imageUrl) {
			if (!imageUrl) return null
			
			let firstImageUrl = null
			
			// 如果是多张图片用逗号分隔
			if (imageUrl.includes(',')) {
				firstImageUrl = imageUrl.split(',')[0].trim()
			}
			// 如果是多张图片用分号分隔
			else if (imageUrl.includes(';')) {
				firstImageUrl = imageUrl.split(';')[0].trim()
			}
			// 如果是JSON数组格式
			else {
				try {
					const images = JSON.parse(imageUrl)
					if (Array.isArray(images) && images.length > 0) {
						firstImageUrl = images[0]
					} else {
						// 单张图片直接使用
						firstImageUrl = imageUrl
					}
				} catch (e) {
					// 不是JSON格式，当作单张图片处理
					firstImageUrl = imageUrl
				}
			}
			
			// 如果图片URL不是完整的HTTP地址，则拼接API基础地址
			if (firstImageUrl && !firstImageUrl.startsWith('http')) {
				// 确保URL以/开头
				if (!firstImageUrl.startsWith('/')) {
					firstImageUrl = '/' + firstImageUrl
				}
				return API_BASE_URL + firstImageUrl
			}
			
			return firstImageUrl
		},
		
		// 图片加载失败处理
		handleImageError(e) {
			console.log('商品图片加载失败:', e)
			// 可以设置默认图片
			e.target.src = '/static/default-product.png'
		}
	}
}
</script>

<style lang="scss" scoped>
.order-list {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.navbar {
	display: flex;
	align-items: center;
	height: 88rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	position: relative;
	
	.navbar-left {
		width: 88rpx;
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		
		.back-icon {
			font-size: 40rpx;
			color: #333;
			font-weight: bold;
		}
	}
	
	.navbar-title {
		flex: 1;
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.navbar-right {
		width: 88rpx;
		height: 88rpx;
	}
}

.status-tabs {
	display: flex;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	
	.tab-item {
		flex: 1;
		padding: 30rpx 0;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		position: relative;
		
		&.active {
			color: #007aff;
			font-weight: bold;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 60rpx;
				height: 4rpx;
				background-color: #007aff;
				border-radius: 2rpx;
			}
		}
	}
}

.order-scroll {
	height: calc(100vh - 88px - 80rpx);
}

.order-item {
	background-color: #fff;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
	padding-bottom: 20rpx;
	border-bottom: 1px solid #f0f0f0;
	
	.order-number {
		font-size: 26rpx;
		color: #666;
	}
	
	.order-status {
		font-size: 26rpx;
		font-weight: bold;
		
		&.status-pending {
			color: #ff9500;
		}
		
		&.status-shipping {
			color: #007aff;
		}
		
		&.status-completed {
			color: #34c759;
		}
		
		&.status-cancelled {
			color: #ff3b30;
		}
	}
}

.product-info {
	display: flex;
	margin-bottom: 30rpx;
	
	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		margin-right: 20rpx;
	}
	
	.product-details {
		flex: 1;
		
		.product-title {
			font-size: 30rpx;
			color: #333;
			margin-bottom: 10rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		
		.product-price {
			font-size: 32rpx;
			color: #ff3b30;
			font-weight: bold;
			margin-bottom: 10rpx;
		}
		
		.order-time {
			font-size: 24rpx;
			color: #999;
		}
	}
}

.order-actions {
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
	
	.action-btn {
		padding: 12rpx 24rpx;
		border-radius: 20rpx;
		font-size: 26rpx;
		border: 1px solid;
		background-color: transparent;
		
		&.cancel-btn {
			color: #ff3b30;
			border-color: #ff3b30;
		}
		
		&.confirm-btn {
			color: #007aff;
			border-color: #007aff;
		}
		
		&.detail-btn {
			color: #666;
			border-color: #ddd;
		}
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
		opacity: 0.5;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
}

.load-more {
	padding: 30rpx 0;
}

.load-more-wrapper {
	padding: 30rpx 0;
	text-align: center;
	
	.loading {
		color: #999;
		
		.loading-text {
			font-size: 28rpx;
		}
	}
	
	.no-more {
		color: #ccc;
		
		.no-more-text {
			font-size: 26rpx;
		}
	}
	
	.load-more {
		color: #666;
		
		.load-more-text {
			font-size: 28rpx;
		}
	}
}
</style>